//
//  YAYIApliyDetailController.m
//  YAYIDoctor
//
//  Created by hxp on 16/5/4.
//  Copyright © 2016年 hxp. All rights reserved.
//

/**
 问题1：优惠后金额的折扣没算（完成）
 问题2：本单优惠选择折扣应该在下面自动生成优惠金额（完成）
 问题3：本单优惠点击完成，视图上移位置不对（完成）
 问题4：添加项目，点击添加应该返回收费详情，而且添加按钮很难点(完成)
 问题5：优惠后金额的折扣没算（完成）
 问题6：删除项目没有更改金额（完成）
 问题7：cell重用问题，格式错乱（完成）
 问题8：没有根据接口数据修改 项目数量
 问题9：如果选择的项目重复，如何处理
 
 */


#import "YAYIApliyDetailController.h"
#import "YAYIServiceContentController.h"
#import "YAYIApilySuccessController.h"
#import "YAYIApilyServicepriceCell.h"
#import "YAYIOrderServiceModel.h"
#import "YAYIApilyDetailCell.h"
#import "YAYIDiscountView.h"
#import "YAYIAvatarCell.h"
#import "YAYIGroupModel.h"
#import "YAYIPatienInfoController.h"


@interface YAYIApliyDetailController ()<UITableViewDelegate,UITableViewDataSource,YAYIDiscountViewDelegate,YAYIAlertViewDelegate,YAYIServiceContentControllerDelegatte, YAYIApilyServicepriceCellDelegate,YAYIApilyDetailCellDelegate, UITextFieldDelegate, UIAlertViewDelegate>

@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)NSMutableArray *dataAry;
@property (nonatomic,strong)UIView *sheetView;
@property (nonatomic,strong)NSString *reduce;
@property (nonatomic,strong)YAYIDiscountView *discountView;
@property (nonatomic,strong)UIAlertController *alertController;
@property (nonatomic,strong)YAYIAlertView *alertView;
@property (nonatomic,strong)NSMutableArray *checkedAry;
@property (nonatomic,copy)NSString *serviceContent;

/** 本单优惠金额 */
@property (nonatomic,weak) UITextField *discountTF;
/** 服务内容 */
@property (nonatomic,weak) UITextField *serviceContentTF;

@end

@implementation YAYIApliyDetailController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"收费详情";
    
    
    self.dataAry = [NSMutableArray array];
    self.checkedAry = [NSMutableArray array];
    [self orderDetail];
    [self createTableView];
    [self createRightBtn];
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view resignFirstResponder];
}


-(void)createTableView
{
    if (self.tableView == nil) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_width, SCREEN_height) style:UITableViewStyleGrouped];
        self.tableView.contentInset = UIEdgeInsetsMake(-35, 0, 0, 0);
        self.tableView.separatorInset = UIEdgeInsetsZero;
        if (SystemVersion >= 8.0) {
            [self.tableView setLayoutMargins:UIEdgeInsetsZero];
        }
        self.tableView.separatorColor = YAYIColor(0xdd, 0xdd, 0xdd);
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        [self.view addSubview:self.tableView];
    }
}


-(void)createRightBtn
{
    
    NSString *rightBtnTitleStr = @"提交";
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [button setImage:[UIImage imageNamed:@"back_button"] forState:UIControlStateNormal];
    [button setTitle:rightBtnTitleStr forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    
    button.frame = (CGRect){{0, 0}, CGSizeMake(50, 30)};
    
    // 让按钮内部的所有内容左对齐
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [button addTarget:self action:@selector(appily:) forControlEvents:UIControlEventTouchUpInside];
    
    // 修改导航栏左边的item
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}



-(void)createActionSheet
{
    
    if (self.sheetView == nil) {
        self.sheetView =[UIView new];
        self.sheetView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.sheetView];
        [self.sheetView  mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(0));
            make.right.equalTo(@(0));
            make.bottom.mas_equalTo(self.view.mas_bottom);
            make.size.mas_equalTo(CGSizeMake(SCREEN_width, 205));
        }];
    }
    UIButton *cButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cButton setTitle:@"取消" forState:UIControlStateNormal];
    cButton.titleLabel.font = [UIFont systemFontOfSize:font14];
    [cButton addTarget:self action:@selector(cancell:) forControlEvents:UIControlEventTouchUpInside];
    [cButton setTitleColor:YAYIColor(83, 165, 243) forState:UIControlStateNormal];
    [self.sheetView addSubview:cButton];
    [cButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(25));
        make.top.equalTo(@(18));
        make.size.mas_equalTo(CGSizeMake(60, 20));
    }];
    UIButton *sButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sButton setTitle:@"完成" forState:UIControlStateNormal];
    sButton.titleLabel.font = [UIFont systemFontOfSize:font14];
    [sButton addTarget:self action:@selector(cancell:) forControlEvents:UIControlEventTouchUpInside];
    [sButton setTitleColor:YAYIColor(83, 165, 243) forState:UIControlStateNormal];
    [self.sheetView addSubview:sButton];
    [sButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view.mas_right).with.offset(-25);
        make.top.equalTo(@(18));
        make.size.mas_equalTo(CGSizeMake(60, 20));
    }];
    
    UIButton *dButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [dButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [dButton setBackgroundImage:[UIImage imageNamed:@"register_button_normal"] forState:UIControlStateNormal];
    dButton.clipsToBounds = YES;
    dButton.layer.cornerRadius = 18;
    [dButton setTitle:@"本单优惠（元）" forState:UIControlStateNormal];
    dButton.titleLabel.font = [UIFont systemFontOfSize:font14];
    
    dButton.tag = 0;
    [dButton addTarget:self action:@selector(discountAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.sheetView addSubview:dButton];
    [dButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(cButton.mas_bottom).with.offset(45);
        make.centerX.mas_equalTo(self.sheetView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(270, 36));
    }];
    
    UIButton *dsButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [dsButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [dsButton setBackgroundImage:[UIImage imageNamed:@"register_button_normal"] forState:UIControlStateNormal];
    dsButton.clipsToBounds = YES;
    dsButton.layer.cornerRadius = 18;
    
    dsButton.tag = 1;
    [dsButton addTarget:self action:@selector(discountAction:) forControlEvents:UIControlEventTouchUpInside];
    [dsButton setTitle:@"本单折扣（％）" forState:UIControlStateNormal];
    dsButton.titleLabel.font = [UIFont systemFontOfSize:font14];
    [self.sheetView addSubview:dsButton];
    [dsButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(dButton.mas_bottom).with.offset(15);
        make.centerX.mas_equalTo(self.sheetView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(270, 36));
    }];
    
}


/**
 *  弹出这折扣选择框
 */
-(void)presentSheetView{
    
    if (self.sheetView == nil) {
        
        [self createActionSheet];
        [self.tableView  setContentOffset:CGPointMake(0, 180) animated:YES];
    }else{
        
        [UIView animateWithDuration:1 animations:^{
            [self.sheetView  mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(@(0));
                make.right.equalTo(@(0));
                make.bottom.mas_equalTo(self.view.mas_bottom);
                make.size.mas_equalTo(CGSizeMake(SCREEN_width, 0));
            }];
        }];
        [self.sheetView removeFromSuperview];
        self.sheetView = nil;
        [self.tableView  setContentOffset:CGPointMake(0, 35) animated:YES];
    }
}


-(void)createDiscounView{
    if (self.discountView == nil) {
        self.discountView = [[YAYIDiscountView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view.frame) - 265, SCREEN_width, 265)];
        self.discountView.delegate = self;
        self.discountView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.discountView];
    }
}


/**
 *  添加项目
 */

-(UIView *)createFooterView
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_width, 44)];
    footerView.backgroundColor = [UIColor  whiteColor];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"添加项目" forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"addItem"] forState:UIControlStateNormal];
    button.frame = CGRectMake(20, (44 - 28)/2.0, 100, 28);
    [button setTitleColor:YAYIColor(83, 165, 243) forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:font16];
    button.layer.borderColor =YAYIColor(83, 165, 243).CGColor;
    button.layer.borderWidth = 0.5;
    button.layer.masksToBounds = YES;
    [button  addTarget:self action:@selector(addContent:) forControlEvents:UIControlEventTouchUpInside];
    button.layer.cornerRadius = 3;
    [footerView addSubview:button];
    return footerView;
}


-(void)section:(NSInteger)section content:(NSString *)content
{
    if (section ==1) {
        self.ordercontent = content;
    }else{
        self.reduce = content;
        self.reducePrice = self.totalPrice - [self.reduce intValue];
    }
    [self createDataSource];
}


/**  计算合计应收 和 优惠后金额  */
- (void)calculateTotalPrice
{
    CGFloat totalPriceTemp = 0;
    for (YAYIServiceModel *model in self.checkedAry) {
        totalPriceTemp += [model.price integerValue] * [model.amount integerValue];
    }
    self.totalPrice = totalPriceTemp;
    
    if (self.discount != 0) {
        self.reducePrice = self.totalPrice - self.totalPrice * self.discount;
    }
    
    
    // 修改总计金额
    YAYIGroupModel *model0 = self.dataAry[4][0];
    YAYIGroupModel *model1 = self.dataAry[4][1];
    
    model0.name = [NSString stringWithFormat:@"%.2f", totalPriceTemp / 100.0];
    
    CGFloat shouldPayAmount = totalPriceTemp - self.reducePrice;
    if (shouldPayAmount < 0) {
        shouldPayAmount = 0;
    }
    model1.name = [NSString stringWithFormat:@"%.2f", shouldPayAmount / 100.0];
    [self.tableView reloadData];
    /*
    if (self.discount > 0 || self.reducePrice == 0) {
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationFade];
    }

    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationFade];
     */
}


#pragma mark - 获取数据
-(void)orderDetail
{
    if (self.orderid != nil) {
        [YAYINetWorking getWithURL:noPay_order_detail_url param:@{@"orderid":self.orderid} finish:^(NSData *data, NSDictionary *dict, NSError *error) {
            
            YAYILog(@"返回：%@",dict);
            
            if ([dict[@"status"] isEqualToString:@"success"]) {
                
                NSDictionary *map = dict[@"map"];
                NSArray *oderServices = map[@"oderServices"];
                for (NSDictionary *obj in oderServices) {
                    
                    YAYIOrderServiceModel *model = [YAYIOrderServiceModel new];
                    [model setValuesForKeysWithDictionary:obj];
                    model.title = model.servicename;
                    [self.checkedAry addObject:model];
                }
                self.serviceContent = map[@"order"][0][@"ordercontent"];
                [self createDataSource];
            }
        }];
        
    }else{
        
        [self createDataSource];
    }
    
}


-(void)createDataSource
{
    [self.dataAry removeAllObjects];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray *group0 = [NSMutableArray array];
        NSMutableArray *group1 = [NSMutableArray array];
        NSMutableArray *group2 = [NSMutableArray array];
        NSMutableArray *group3 = [NSMutableArray array];
        YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
        group.avatar = [NSString stringWithFormat:@"%@%@",API,_avatar];
        group.name = [NSString  stringWithFormat:@"%@ (%@)",_patientname,_clientname];
        group.phone = self.mobile;
        [group0 addObject:group];
        
        NSArray *titleAry = @[@"就诊医院"];
        NSArray *name = @[_hospital];
        
        for (int i = 0; i< name.count; i ++) {
            YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
            group.title = titleAry[i];
            group.name = name[i];
            [group1  addObject:group];
        }
        
        NSArray *title1 = @[@"合计应收",@"优惠后金额"];
        NSArray *name1 = @[[NSString stringWithFormat:@"%.2f", self.totalPrice / 100],[NSString stringWithFormat:@"%.2f", (self.totalPrice - self.reducePrice) / 100]];
        for (int i = 0; i< name1.count; i ++) {
            YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
            group.title = title1[i];
            group.name = name1[i];
            [group2  addObject:group];
        }
        NSArray *title2 = @[@"收款方式"];
        NSArray *name2 = @[@"在线支付"];
        for (int i = 0; i< name2.count; i ++) {
            YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
            group.title = title2[i];
            group.name = name2[i];
            [group3  addObject:group];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.dataAry addObject:group0];
            [self.dataAry addObject:group1];
            [self.dataAry addObject:self.checkedAry];
            [self.dataAry addObject:group3];
            [self.dataAry addObject:group2];
            [self.dataAry addObject:group3];
            [self.tableView     reloadData];
        });
    });
}


/**
 *  修改订单
 */
-(void)createOrder
{
    
    //    if (self.sercontent.length == 0) {
    //        return;
    //    }
    
    if (self.reduce == nil) {
        self.reduce = @"0";
    }
    
    NSInteger dataCount = self.checkedAry.count;
    NSMutableString *servicesStr = [NSMutableString string];
    for (int i = 0; i < dataCount; i++) {
        
        YAYIOrderServiceModel *model = self.checkedAry[i];
        [servicesStr appendFormat:@"%@,", model.serviceid];
        [servicesStr appendFormat:@"%@", model.amount];
        
        if (i != dataCount - 1) {
            
            [servicesStr appendString:@";"];
        }
    }
    
    
    if (self.orderid != nil) {
        
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"orderid"] = self.orderid;
        param[@"totalprice"] = @(self.totalPrice);
        param[@"reduce"] = @(self.reducePrice);
        param[@"services"] = [servicesStr copy];
        param[@"orderid"] = self.orderid;
        param[@"ordercontent"] = self.serviceContent;
        
        YAYILog(@"%@",param);
        
        [YAYINetWorking postJsonSerilizeWithURL:update_order param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
            
            if (nil == error) {
                
                YAYILog(@"返回：%@", dict);
                
                if ([dict[@"status"] isEqualToString:@"success"]) {
                    
//                    YAYIApilySuccessController *success = [YAYIApilySuccessController new];
//                    success.title = @"提交结果";
//                    [self.navigationController pushViewController:success animated:YES];
                    [SVProgressHUD showImage:nil status:@"\n\n修改成功\n\n"];
                    
                    __block typeof(self) weakself = self;
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        if (self.refreshOperation) {
                            weakself.refreshOperation();
                        }
                        
                        [weakself.navigationController popViewControllerAnimated:YES];
                    });
                    
                }else{
                    
                    YAYIHudProgressView *hud = [[YAYIHudProgressView alloc] initWithView:self.view.window];
                    [hud setMessage:@"提交失败"];
                    [[UIApplication  sharedApplication].keyWindow addSubview:hud];
                    [hud removeFromSuperview:YES time:1 isHinden:YES];
                    
                }
                
            }else{
                NSString *message = responseError[@"message"];
                YAYIHudProgressView *hud = [[YAYIHudProgressView alloc] initWithView:self.view.window];
                
                YAYILog(@"message:%@", message);
                
                [hud setMessage:message];
                [[UIApplication  sharedApplication].keyWindow addSubview:hud];
                [hud removeFromSuperview:YES time:1 isHinden:YES];
            }
        }];
        
    }else{
        
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"bookingid"] = self.bookingid;
        param[@"hospitalid"] = self.hospitalid;
        param[@"ordercontent"] = self.serviceContent;
        param[@"totalprice"] = @(self.totalPrice);
        param[@"reduce"] = @(self.reducePrice);
        param[@"services"] = [servicesStr copy];
        param[@"userid"] = self.userid;
        
        [YAYINetWorking postJsonSerilizeWithURL:build_order param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
            
            YAYILog(@"返回：%@", dict);
            if (error == nil) {
                if ([dict[@"status"] isEqualToString:@"success"]) {
                    
                    YAYIApilySuccessController *success = [YAYIApilySuccessController new];
                    success.title = @"提交结果";
                    [self.navigationController pushViewController:success animated:YES];
                }else{
                    YAYIHudProgressView *hud = [[YAYIHudProgressView alloc] initWithView:self.view.window];
                    [hud setMessage:@"提交失败"];
                    [[UIApplication  sharedApplication].keyWindow addSubview:hud];
                    [hud removeFromSuperview:YES time:1 isHinden:YES];
                }
                
            }else{
                NSString *message = responseError[@"message"];
                YAYIHudProgressView *hud = [[YAYIHudProgressView alloc] initWithView:self.view.window];
                [hud setMessage:message];
                [[UIApplication  sharedApplication].keyWindow addSubview:hud];
                [hud removeFromSuperview:YES time:1 isHinden:YES];
            }
        }];
        
    }
    
}


#pragma mark - 点击事件
-(void)addContent:(UIButton *)sender
{
    YAYIServiceContentController *serviceContent = [YAYIServiceContentController new];
    serviceContent.title = @"项目和单价";
    serviceContent.delegate = self;
    serviceContent.hospitalid = self.hospitalid;
    
    [self.navigationController pushViewController:serviceContent animated:YES];

}

/**
 *  选择本单优惠，点击了取消或完成
 */
-(void)cancell:(UIButton *)sender
{

    [UIView animateWithDuration:0.8f animations:^{
        CGRect rect = self.sheetView.frame;
        rect.origin.y =  rect.origin.y + 225;
        self.sheetView.frame = rect;
        self.tableView.contentOffset = CGPointMake(0, 35);
    }];
    [self.sheetView removeFromSuperview];
    self.sheetView = nil;
}


/**
 *  点击本单折扣
 */
-(void)discountAction:(UIButton *)sender
{
    if (0 == sender.tag) {
        
        self.reducePrice = 0;
        self.discount = 0;
        [self calculateTotalPrice];
        
        [UIView animateWithDuration:0.3 animations:^{

            [self.sheetView  mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(@(0));
                make.right.equalTo(@(0));
                make.bottom.mas_equalTo(self.view.mas_bottom);
                make.size.mas_equalTo(CGSizeMake(SCREEN_width, 0));
            }];
            
        } completion:^(BOOL finished) {
            
            [self.sheetView removeFromSuperview];
            self.sheetView = nil;
            
        }];
        [self.tableView  setContentOffset:CGPointMake(0, 35) animated:YES];
        
    }else if (1 == sender.tag){
        
        [self presentSheetView];
        if (self.discountView == nil) {
            [self createDiscounView];
            [self.tableView  setContentOffset:CGPointMake(0, 180) animated:YES];
        }else{
            
            [self.discountView removeFromSuperview];
            self.discountView = nil;
        }
        
    }
}


/**
 *  提交
 */
-(void)appily:(UIButton *)sender{
    
    [self.view endEditing:YES];
    
    CGFloat shouldPayAmount = self.totalPrice - self.reducePrice;
    if (shouldPayAmount <= 0) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"优惠金额必须小于应付总额，请重新输入" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 100;
        [alert show];
        return;
    }
    
    // 判断服务内容是否为空
    if (self.serviceContent.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"服务内容不能为空，请输入" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 300;
        [alert show];
        return;
    }

    NSString *titleStr = [NSString stringWithFormat:@"本单合计实收%.2f元，确定提交吗？" , (self.totalPrice - self.reducePrice) / 100];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:titleStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 200;
    [alert show];
    
}


#pragma mark - 代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return self.dataAry.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) { // 头部cell
        static NSString *identifer = @"avatarCell";
        YAYIAvatarCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (cell == nil) {
            cell = [[YAYIAvatarCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
        }
        YAYIGroupModel *model = self.dataAry[indexPath.section][indexPath.row];
        [cell.avatar sd_setImageWithURL:[NSURL URLWithString:model.avatar] placeholderImage:[UIImage imageNamed:@"1"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
        }];
        cell.phone.text = model.phone;
        cell.name.text =  model.name;
        cell.icon.hidden = NO;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.section == 2) {  // 项目
        
        static NSString *ident = @"itemCell";
        YAYIApilyServicepriceCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
        if (cell == nil) {
            cell = [[YAYIApilyServicepriceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident];
        }
        cell.delegate = self;
        cell.model = self.checkedAry[indexPath.row];
        [cell.deleteBtn addTarget:self action:@selector(onDeleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        cell.tag = indexPath.row;
        cell.deleteBtn.tag = indexPath.row;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }else{  //
        static NSString *identifer = @"accountCell";

        // 这里不重用，否则格式会乱
        YAYIApilyDetailCell *cell = [[YAYIApilyDetailCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
        cell.delegate = self;
        cell.section = indexPath.section;
        cell.row = indexPath.row;
        if (indexPath.section == 1 && indexPath.row == 0) { // 就诊医院
            
            YAYIGroupModel *model = self.dataAry[indexPath.section][indexPath.row];
            cell.title.text = model.title;
            cell.name.text = model.name;
            
        }else if (indexPath.section == 1 && indexPath.row == 1) { // 服务内容
            
            self.serviceContentTF = cell.textfield;
            cell.title.text = @"服务内容";
            cell.textfield.delegate = self;
            cell.textfield.text = self.serviceContent;
            cell.textfield.tag = indexPath.section;
            [cell.textfield addTarget:self action:@selector(textFieldTextChanged:) forControlEvents:UIControlEventEditingChanged];
        }else if (indexPath.section == 3 && indexPath.row == 0){ // 本单优惠
            
            cell.title.text = @"本单优惠 （元）";
            
        }else if (indexPath.section == 3 && indexPath.row == 1){ // 填写金额
            
            self.discountTF = cell.textfield;
            cell.textfield.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
            cell.textfield.delegate = self;
            cell.textfield.tag = indexPath.section;
            [cell.textfield addTarget:self action:@selector(textFieldTextChanged:) forControlEvents:UIControlEventEditingChanged];
            
            if (self.reducePrice > 0) {
                cell.textfield.text = [NSString stringWithFormat:@"%.2f", self.reducePrice / 100];
            }else{
                cell.textfield.text = nil;
            }
        }if (indexPath.section == 4 || indexPath.section == 5) { // 合计应收、优惠金额、收款方式
            
            YAYIGroupModel *model = self.dataAry[indexPath.section][indexPath.row];
            cell.title.text = model.title;
            
            cell.name.text = model.name;
            
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (SystemVersion >= 8.0) {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
        
        return cell;
    }
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return [self.dataAry[section] count];
    }else if (section == 2){
        return self.checkedAry.count;
    }else if (section == 5){
        return 1;
    }
    return 2;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 80;
    }else if (indexPath.section == 2){
        return 88;
    }
    return 44;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 2) {
        return 44;
    }
    return 10;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 3) {
        return 10;
    }
    return 0.01;
}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 2) {
        return [self createFooterView];
    }
    return [UIView new];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    if (indexPath.section ==2) {
        
        
    }else if (indexPath.section == 3 && indexPath.row ==0) {
        
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
        [self presentSheetView];
        if (self.discountView != nil) {
            [self.discountView removeFromSuperview];
            self.discountView = nil;
        }
    }else if (indexPath.section == 0){
    
        YAYIPatienInfoController *patientInfoVc = [[YAYIPatienInfoController alloc] init];
        patientInfoVc.isAccepted = YES;
        patientInfoVc.userid = [NSString stringWithFormat:@"%@", self.userid];
        YAYILog(@"patientInfoVc.userid:%@", patientInfoVc.userid);
        [self.navigationController pushViewController:patientInfoVc animated:YES];
    }
}


#pragma mark UITextField代理
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    YAYILog(@"textField.tag:%ld", textField.tag);
    if (textField.tag != 1) {
        [UIView animateWithDuration:0.3 animations:^{
            self.view.y -= 200;
        }];
    }
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShowAction:) name:UIKeyboardWillShowNotification object:nil];
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField.tag != 1) {
        [UIView animateWithDuration:0.3 animations:^{
            self.view.y += 200;
        }];
    }
    
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    
    
    return !(self.discount > 0);
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


- (void)textFieldTextChanged:(UITextField *)textField
{
    if (textField.tag == 1) {   // 服务内容
        
        self.serviceContent  = textField.text;
    }else{  // 修改总计金额
        
        NSString *textStr = textField.text;
        double money = [textStr doubleValue];
        self.reducePrice = money * 100;
        
        // 修改总计金额
        YAYIGroupModel *model1 = self.dataAry[4][1];
        CGFloat shouldPayAmount = self.totalPrice - self.reducePrice;
        if (shouldPayAmount < 0) {
            shouldPayAmount = 0;
        }
        model1.name = [NSString stringWithFormat:@"%.2f", shouldPayAmount / 100.0];
        
        NSIndexPath *idnexPath = [NSIndexPath indexPathForRow:1 inSection:4];
        [self.tableView reloadRowsAtIndexPaths:@[idnexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillhideAction:) name:UIKeyboardWillHideNotification object:nil];
    
}

//-(void)keyboardWillhideAction:(NSNotificationCenter *)center
//{
//    
//    [self calculateTotalPrice];
//
//}

//-(void)keyBoardWillShowAction:(NSNotificationCenter *)center{
//
//    if (self.sheetView!= nil) {
//        self.sheetView.hidden = YES;
//        self.view.y  += 200;
//        [self.sheetView removeFromSuperview];
//        self.sheetView = nil;
//    }
//}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
   [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

#pragma mark YAYIApilyServicepriceCell代理
-(void)orderCount:(int)cout price:(NSString *)price model:(YAYIServiceModel *)model
{
    if (cout == 0) {
        return;
    }
    
    self.totalPrice = 0;
    for (YAYIServiceModel *mdel in self.checkedAry) {
        if ([mdel.title  isEqualToString:model.title]) {
            
            mdel.amount = [NSString stringWithFormat:@"%d", cout];
            [self calculateTotalPrice];
        }
    }
}


- (void)onDeleteBtnClick:(UIButton *)sender
{
    // 删除数据
    [self.checkedAry removeObjectAtIndex:sender.tag];
    
    // 删除cell
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:2];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
    [self calculateTotalPrice];
}


#pragma mark YAYIServiceContentControllerDelegatte代理
- (void)serviceChecked:(NSMutableArray *)serviceItemArray
{

    // 数组换成字典, 为避免选择了重复的项目
    NSMutableDictionary *modelDict = [NSMutableDictionary dictionary];
    for (int i = 0; i < self.checkedAry.count; i++) {
        
        YAYIServiceModel *model = self.checkedAry[i];
        modelDict[model.serviceid] = @(i);
    }
    
    for (YAYIServiceModel *mdel in serviceItemArray) {
        
        NSString *valueStr = modelDict[mdel.serviceid];
        if (valueStr) {
            
            YAYIServiceModel *hadModel = self.checkedAry[[valueStr integerValue]];
            NSInteger amount = [hadModel.amount integerValue] + 1;
            hadModel.amount = [NSString stringWithFormat:@"%ld", amount];
        }else{
            
            [self.checkedAry addObject:mdel];
        }
    }
    
    [self calculateTotalPrice];
}



#pragma mark YAYIDiscountView代理
-(void)discount:(NSString *)discount
{
    self.discount = [discount intValue] * 0.01;
    self.reducePrice  = self.totalPrice - self.discount * self.totalPrice;
//    self.reducePrice = self.totalPrice;
    
    [self.tableView  setContentOffset:CGPointMake(0, 35) animated:YES];
//    [self createDataSource];
    [self calculateTotalPrice];
}


#pragma mark YAYIAlertView代理
//-(void)alertView:(YAYIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    alertView = nil;
//    self.alertView = nil;
//    if (buttonIndex == 2) {
//        
//        [self createOrder];
//        
//    }
//}

#pragma mark UIAlertView代理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (alertView.tag == 100) { // 优惠金额大于应收金额提示
        
        [self.discountTF becomeFirstResponder];
    }else if (alertView.tag == 200){ // 点击提交提示
        
        if (buttonIndex == 1) {
            
//            YAYIApilySuccessController *success = [YAYIApilySuccessController new];
//            success.title = @"提交结果";
//            [self.navigationController pushViewController:success animated:YES];
            [self createOrder];
        }
    }else if (alertView.tag == 300){ // 点击提交提示
        
        [self.serviceContentTF becomeFirstResponder];
    }
}


@end
